﻿using Dotnet.Code;
using Microsoft.AspNetCore.Mvc;
using Wutos.App;
using Wutos.Code;
using Wutos.Domain;
using static Wutos.App.SportApp;

namespace Clock.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SportController : ControllerBase
    {
        private readonly ILogger<SportController> _logger;

        public SportController(ILogger<SportController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string GetNum([FromQuery] string param)
        {
            Wutos.App.SportApp sportApp = new Wutos.App.SportApp();
            if (param == "0") return sportApp.GetList().ToJson();
            return sportApp.GetList(param).ToJson();
        }
        [HttpGet]
        public string GetToday([FromQuery] string date)
        {
            Wutos.App.SportApp sportApp = new Wutos.App.SportApp();
            DateTime dt;
            bool isDateTime = DateTime.TryParse(date, out dt);
            if (isDateTime == false) {
                throw new Exception($"{date}时间格式化错误");
            }
            DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
            return sportApp.GetList(dt).ToJson();
        }

        [HttpGet]
        public string GetMonthData([FromQuery] string startYmd,string endYmd)
        {
            Wutos.App.SportApp sportApp = new Wutos.App.SportApp();
            DateTime dtStart,dtEnd;
            bool isdtStart = DateTime.TryParse(startYmd, out dtStart);
            if (isdtStart == false)
            {
                throw new Exception($"{startYmd}时间格式化错误");
            }
            bool isdtEnd = DateTime.TryParse(endYmd, out dtEnd);
            DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
            return sportApp.GetList(dtStart,dtEnd).ToJson();
        }

        [HttpPost]//data: { name: name, addtime: startTime, mtime: endTime, second: spanTime },
        //[Consumes("application/x-www-form-urlencoded")]
        public string Post([FromForm] SportEntity entity)
        {
            try
            {
                string[] daysOfWeek = { "日", "一", "二", "三", "四", "五", "六" };
                entity.week = daysOfWeek[(int)entity.addtime.DayOfWeek];
                SportApp sportApp = new SportApp();
                sportApp.Save(entity);
                return "OK";
            }
            catch (Exception ex)
            {
                return $"FIAL:{ex.Message}";
            }
        }
        [HttpGet]
        public JsonResult Delete(int id)
        {
            SportApp app = new SportApp();
            int ret=app.Delete(id);
            if (ret == 1) return new JsonResult("OK");
            return new JsonResult("FAIL");
        }
    }
}
